import java.util.Deque;
import java.util.LinkedList;

class Solution {
    // 两次扫描
    public int longestValidParentheses(String s) {
        int left = 0, right = 0, maxlength = 0;
        for (int i = 0; i < s.length(); i++){
            if (s.charAt(i) == '('){
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxlength = Math.max(maxlength, 2*left);
            } else if (left < right) {
                left = 0;
                right = 0;
            }
        }

        left = 0;
        right = 0;
        for (int i = s.length()-1; i >= 0; i--){
            if (s.charAt(i) == '('){
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxlength = Math.max(maxlength, 2*left);
            } else if (left > right) {
                left = 0;
                right = 0;
            }
        }

        return maxlength;
    }

    // 栈
    public int longestValidParentheses(String s) {
        int ans = 0;
        Deque<Integer> stack = new LinkedList<Integer>();
        stack.push(-1);
        for (int i = 0; i < s.length(); i++){
            if (s.charAt(i) == '('){
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()){
                    stack.push(i);
                } else {
                    ans = Math.max(ans, i-stack.peek());
                }
            }
        }
        return ans;
    }

    // 动态规划

}